﻿using System;
namespace Jumbot.API.Discuz
{
    /// <summary>
    /// 此接口只是单向的整合，JumbotCms的注册、登录、注销等会同时影响Discuz
    /// 但反向的Discuz的注册、登录、注销等不会影响JumbotCms
    /// 适合环境：JumbotCms作为主站点，而Discuz做为虚拟目录（具有独立的应用程序名）
    /// 暂且可命名为Jumbot.API，特点是不改变论坛的任何文件，缺点是不支持跨站
    /// 稍后可能会出Discuz.API2JumbotCms、或Discuz.AndJumbotCms
    /// </summary>
    public class Command
    {
        public static IDbProvider DBC;
        public static IDbCommand IDC;

        private static EnCode EC;
        public static ReadConfig RC;

        static Command()
        {
            RC = new ReadConfig();
            EC = new EnCode();
            DBC = (IDbProvider)Activator.CreateInstance(Type.GetType(String.Format("Jumbot.API.Discuz.{0}Command", RC.DBType), false, true));
            IDC = (IDbCommand)Activator.CreateInstance(Type.GetType(String.Format("Jumbot.API.Discuz.{0}DbCom", RC.DBType), false, true));
            DBC.vDataBaseConnectionString = RC.BbsDbConnection;
        }

        /// <summary>
        /// 同步注册
        /// </summary>
        /// <param name="username">帐号</param>
        /// <param name="gender">性别</param>
        /// <param name="nickname">昵称</param>
        /// <param name="password">密码(未加密)</param>
        /// <param name="email">邮箱</param>
        /// <param name="groupid">会员隶属组</param>
        /// <param name="regip">注册IP</param>
        /// <param name="qq">QQ号</param>
        /// <param name="msn">MSN</param>
        /// <returns>是否注册成功</returns>
        public static bool Register(string username, int gender, string nickname, string password, string email, int groupid, string regip, string qq, string msn)
        {
            return IDC.Register(username, gender, nickname, password, email, groupid, regip, qq, msn);
        }

        public static bool Register(string username, int gender, string nickname, string password, string email, int groupid)
        {
            return Register(username, gender, nickname, password, email, groupid, RC.UserIP, String.Empty, String.Empty);
        }
        public static bool Register(string username, int gender, string nickname, string password, string email)
        {
            return Register(username, gender, nickname, password, email, Command.RC.DefaultGroup, RC.UserIP, String.Empty, String.Empty);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="username">帐号</param>
        /// <param name="password">密码(未加密)</param>
        /// <returns>是否修改成功</returns>
        public static bool ModifyPwd(string username, string password)
        {
            return IDC.ModifyPwd(username, password);
        }

        /// <summary>
        /// 同步登陆
        /// </summary>
        /// <param name="username">帐号</param>
        /// <param name="password">密码(未加密)</param>
        /// <param name="expDays">有效期</param>
        /// <param name="inVisible">是否隐身</param>
        /// <param name="reFerer">返回页面</param>
        /// <returns>是否登陆成功</returns>
        public static bool Login(string username, string password, int expDays, bool inVisible, string reFerer)
        {
            return IDC.Login(username, password, expDays, inVisible, reFerer);
        }
        public static bool Login(string username, string password, int expDays)
        {
            return Login(username, password, expDays, false, "index.aspx");
        }
        public static bool Login(string username, string password)
        {
            return Login(username, password, 0, false, "index.aspx");
        }

        /// <summary>
        /// 同步退出
        /// </summary>
        public static void LoginOut()
        {
            IDC.LoginOut();
        }

        /// <summary>
        /// 当前模式的MD5加密
        /// </summary>
        /// <param name="Input">要加密的字串</param>
        /// <returns>加密后的字串</returns>
        public static string Md5(string Input)
        {
            string md5str = EC.md5(Input);
            return (RC.PasswordMode == 0) ? md5str : md5str.Substring(8, 16);
        }

        /// <summary>
        /// 当前模式的Des加密
        /// </summary>
        /// <param name="Input">要加密的字串</param>
        /// <returns>加密后的字串</returns>
        public static string DesEncode(string Input)
        {
            return EC.DESEncode(Input, RC.PasswordKey);
        }

        /// <summary>
        /// 数据库操作最后一次的错误信息
        /// </summary>
        public static string DbLastError
        {
            get
            {
                return DBC.vErrorResultString;
            }
        }

        /// <summary>
        /// 检测域
        /// </summary>
        /// <param name="doMain">域名</param>
        /// <returns>是否为有效域</returns>
        public static bool IsValidDomain(string doMain)
        {
            string host = System.Web.HttpContext.Current.Request.Url.Host;
            if (String.IsNullOrEmpty(doMain) || host.IndexOf(doMain) < 0) return false;
            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"^\d+$");
            if (host.IndexOf(".") == -1) return false;
            return !(r.IsMatch(host.Replace(".", String.Empty)));
        }

        /// <summary>
        /// 写入登陆COOKIES信息
        /// </summary>
        /// <param name="userinfo"></param>
        /// <param name="inVisible"></param>
        /// <param name="reFerer"></param>
        /// <param name="expDays"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        internal static bool WriteLoginCookie(GetUserInfo userinfo, bool inVisible, string reFerer, int expDays, string password)
        {
            //try
            //{
            System.Web.HttpCookie cookie = new System.Web.HttpCookie("dnt");
            cookie.Values["userid"] = userinfo.Uid;
            if (password.Length == 32)//表示密文
                cookie.Values["password"] = System.Web.HttpUtility.UrlEncode(DesEncode(password));
            else
                cookie.Values["password"] = System.Web.HttpUtility.UrlEncode(DesEncode(Md5(password)));
            cookie.Values["tpp"] = userinfo.Tpp;
            cookie.Values["ppp"] = userinfo.Ppp;
            cookie.Values["pmsound"] = userinfo.Pmsound;
            cookie.Values["invisible"] = inVisible ? "0" : "1";
            cookie.Values["referer"] = reFerer;
            cookie.Values["sigstatus"] = userinfo.Sigstatus;
            cookie.Values["expires"] = expDays.ToString();
            if (IsValidDomain(RC.doMain))
            {
                cookie.Domain = Command.RC.doMain;
            }
            cookie.Path = "/";
            if (expDays > 0) cookie.Expires = DateTime.Now.AddDays(expDays);
            System.Web.HttpContext.Current.Response.AppendCookie(cookie);
            return true;
            //}
            //catch (Exception ex)
            //{
            //    return false;
            //}
        }
    }
}